<?php defined('SYSPATH') or die('No direct script access.');
require_once TOOLS_COMMON . 'sms/noticecommon.php';

/**
 * 邮件发送公共类.
 * User: Administrator
 * Date: 16-6-17
 * Time: 下午4:49
 */
class QywxService
{

    public static function send_qywx($url, $title, $content){
        $res= self::sendRequest($url,json_encode(['msgtype'=>'text','text'=>['content'=>"【{$title}】\n\r".$content]]), 'POST');
        if($res['errno']==-1){
            $res = json_decode($res['data'],true);
            St_Log::write('企业微信机器人', $res, "qywx/log");
            return $res;
        }
    }
    public static function sendRequest($url, $params = [], $method = 'POST', $options = []) {
        $method = strtoupper ($method);
        $protocol = substr ($url, 0, 5);
        $query_string = is_array ($params) ? http_build_query ($params) : $params;
        $ch = curl_init ();
        $defaults = [];
        if ('GET' == $method) {
            $geturl = $query_string ? $url . (stripos ($url, "?") !== false ? "&" : "?") . $query_string : $url;
            $defaults[CURLOPT_URL] = $geturl;
        } else {
            $defaults[CURLOPT_URL] = $url;
            if ($method == 'POST') {
                $defaults[CURLOPT_POST] = 1;
            } else {
                $defaults[CURLOPT_CUSTOMREQUEST] = $method;
            }
            $defaults[CURLOPT_POSTFIELDS] = $query_string;
        }
        $defaults[CURLOPT_HEADER] = false;
        $defaults[CURLOPT_USERAGENT] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.98 Safari/537.36";
        $defaults[CURLOPT_FOLLOWLOCATION] = true;
        $defaults[CURLOPT_RETURNTRANSFER] = true;
        $defaults[CURLOPT_CONNECTTIMEOUT] = 3;
        $defaults[CURLOPT_TIMEOUT] = 3;
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Expect:'));
//				json格式提交
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        if ('https' == $protocol) {
            $defaults[CURLOPT_SSL_VERIFYPEER] = false;
            $defaults[CURLOPT_SSL_VERIFYHOST] = false;
        }
        curl_setopt_array ($ch, (array)$options + $defaults);
        $output = curl_exec ($ch);
        $data=[];
        if($output===false){
            $data['msg'] = curl_error($ch);
            $data['errno'] = curl_errno($ch);
            $data['info'] =  curl_getinfo ($ch);
            $data['data'] =  [];
            curl_close ($ch);
        }else{
            $data['msg'] = '';
            $data['errno'] = -1;
            $data['info'] =  curl_getinfo ($ch);
            $data['data'] =  $output;
            curl_close ($ch);
        }
        return $data;
    }

    /*
	 *@function 产品订单特定事件邮件发送
	 *@param string $msgtag,产品订单特定事件类型，NoticeCommon::PRODUCT_ORDER_UNPROCESSING_MSGTAG：订单未处理；NoticeCommon::PRODUCT_ORDER_PROCESSING_MSGTAG：订单处理中；NoticeCommon::PRODUCT_ORDER_PAYSUCCESS_MSGTAG：订单处理中支付成功；NoticeCommon::PRODUCT_ORDER_CANCEL_MSGTAG：订单被取消；
	 *@param array $order_info,订单详细信息.
     *@return bool
	 * */
    public static function send_product_order_qywx($msgtag, array $order_info)
    {
        $result = true;

        $cfg_webname = functions::get_sys_para("cfg_webname");
        //平台管理员的通知地址
        $cfg_qywx_admin_url = Model_Sysconfig::get_sys_conf('value','cfg_qywx_admin_url');

        $content = NoticeCommon::generate_product_order_msg_content($msgtag, NoticeCommon::QYWX_MSGTYPE, $order_info);
        foreach ($content as $content_recipient => $content_item) {
            if (strlen($content_item['content']) <= 0) {
                $result = false;
                continue;
            }
            if ($content_item['isopen'] == 0) {
                $result = false;
                continue;
            }
            //通知管理员
            if ($content_recipient == 'administrator') {
                if (empty($cfg_qywx_admin_url)) {
                    $result = false;
                    continue;
                }
                $title = "预订" . $order_info['productname'] . '[' . $cfg_webname . ']';
                if (!self::send_qywx($cfg_qywx_admin_url, $title, $content_item['content'])) //发送
                {
                    $result = false;
                }
            }
            //通知对应供应商
            if ($content_recipient == 'supplier' && !empty($order_info['supplierlist'])) {
                $supplier=$order_info['supplierlist'];
                $cfg_qywx_admin_url_supplier=Model_Sysconfig::get_sys_conf('value','cfg_qywx_admin_url_supplier_'.$supplier);
                if (empty($cfg_qywx_admin_url_supplier)) {
                    $result = false;
                    continue;
                }
                $title = "预订" . $order_info['productname'] . '[' . $cfg_webname . ']';
                if (!self::send_qywx($cfg_qywx_admin_url_supplier, $title, $content_item['content'])) //发送
                {
                    $result = false;
                }
            }
        }
        return $result;
    }


    //提现发送
    public static function send_withdraw_qywx($msgtag,$withdraw_info) {
        $result = array('Success' => false, 'Message' => '', 'Data' => null);
        $content = NoticeCommon::generate_withdraw_msg_content($msgtag,NoticeCommon::QYWX_MSGTYPE,$withdraw_info );
        St_Functions::writeLog($content,__LINE__);
        if ($content['isopen'] == 0) {
            return $result;
        }
        if (empty($content['recipient']) || strlen($content['content']) <= 0) {
            return $result;
        }
        return self::send_qywx($content['recipient'], '提现通知', $content['content']);
    }

} 